<?php

namespace app\admin\model;

use think\Model;
use traits\model\SoftDelete;
use think\Config;

class Article extends Model
{
    //软删除
    use SoftDelete;
    protected $deleteTime = 'delete_time';
    //把全局自动写入时间戳关闭
    protected $autoWriteTimestamp = FALSE;
    //自动完成
    protected $insert = [];

    //关联分类模型
    public function column()
    {
        return $this->belongsTo('Column', 'column_id', 'id');
    }

    //事件
    protected static function init()
    {
//        self::afterDelete(function($thisObj){
//            //删除文章时把附件也删除（只删除缩略图）
//            if (!empty($thisObj->pic)){
//                delFile($thisObj->pic);
//            }
//        });
        self::beforeUpdate(function ($thisObj){
            if (!empty($thisObj->pic) && stripos($thisObj->pic,'temp')){
                $thisObj->pic = temp_to_uploads($thisObj->pic);
            }
        });
        self::beforeInsert(function ($thisObj){
            if (!empty($thisObj->pic)){
                $thisObj->pic = temp_to_uploads($thisObj->pic);
            }
        });
    }

    //发布状态
    protected function getStatusAttr($value)
    {
        $data = ['<span style="color:#009688;" >已经发布</span>', '<span style="color:#FF5722;" >等待审核</span>', '<span style="color:#1E9FFF;" >已存草稿</span>'];
        return $data[$value];
    }

    //浏览权限
    protected function getIsopenAttr($value)
    {
        $data = ['<span style="color:#1E9FFF;" >开放浏览</span>', '<span style="color:#FF5722;" >私自浏览</span>'];
        return $data[$value];
    }

    //时间戳转日期
    protected function getCreateTimeAttr($value)
    {
        return date("Y-m-d h:i:s", $value);
    }

    /*
     * 数据列表
     * */
    public static function mAll($page = 1, $limit = 15, $data = [])
    {
        if (0 === count($data) && $data === []) {

            if (request()->controller() === 'Recycle') {
                $rel = self::onlyTrashed()->with(['column' => function ($query) { $query->useSoftDelete('id', ['>', 0])->field('id,name'); }])->order('create_time desc')->paginate($limit, FALSE, ['page' => $page])->toArray();
            } else {
                $rel = self::with(['column' => function ($query) { $query->field('id,name'); }])->order('create_time desc')->paginate($limit, FALSE, ['page' => $page])->toArray();
            }
        } else {
            //时间条件判断
            if (isset($data['start'])) {
                $map['create_time'] = ['> time', $data['start']];
            } else if (isset($data['end'])) {
                $map['create_time'] = ['< time', $data['end']];
            } else if (isset($data['start']) && isset($data['end'])) {
                $map['create_time'] = ['between time', [$data['start'], $data['end']]];
            }
            //管理员判断
            if (isset($data['title'])) {
                $map['title'] = ['like', '%' . $data['title'] . '%'];
            }

            if (request()->controller() === 'Recycle') {
                $rel = self::onlyTrashed()->with(['column' => function ($query) { $query->useSoftDelete('id', ['>', 0])->field('id,name'); }])->where($map)->paginate($limit, FALSE, ['page' => $page, 'query' => $map])->toArray();
            } else {
                $rel = self::with(['column' => function ($query) { $query->field('id,name'); }])->where($map)->paginate($limit, FALSE, ['page' => $page, 'query' => $map])->toArray();
            }
        }
//        halt($rel);
        if (FALSE != $rel) {
            if (0 != $rel['total']) {
                $data['code'] = 0;
                $data['msg'] = '数据请求成功！';
                $data['count'] = $rel['total'];
                $data['data'] = $rel['data'];
            } else {
                $data['code'] = 0;
                $data['msg'] = '数据请求成功！';
            }
            return $data;
        }
        return return_json(0, '数据请求失败');
    }

    /*数据增加与修改
     * */
    public static function mSave($data = [], $method = ['create', '增加'])
    {
        if (isset($data['keywords'])) {
            $data['keywords'] = implode(',', array_filter(explode(',', str_replace('，', ',', $data['keywords']))));
        }
        if (empty($data['publish_time'])) {
            $data['create_time'] = time();
        } else {
            $data['create_time'] = strtotime($data['publish_time']);
        }
//        halt($data);
        if ('update' == $method[0]) {
            $rel = self::update($data, ['id' => $data['id']], TRUE);
        } else {
            $rel = self::create($data, TRUE);
        }
        if (FALSE !== $rel) {
            return return_json(0, $method[1] . '成功！');
        }
        return return_json(1, $method[1] . '失败！');
    }

    /*删除
     * */
    public static function mDel($data = [])
    {
        if (1 !== count($data) && $data) {
            $data[0] = implode(',', $data);
        }
        $rel = self::destroy($data[0]);
        if (FALSE != $rel) {
            return return_json(0, '删除成功！', 0);
        } else {
            return return_json(1, '删除失败！');
        }
    }

    /*数据恢复
     * */
    public static function mRestore($data = [])
    {
//        halt($data);

        if (1 !== count($data) && $data) {

            $data[0] = implode(',', $data);
            $temp = [];

            $thisObj = self::onlyTrashed()->select($data[0]);

            if ($thisObj) {

                foreach ($thisObj as $k => $v) {
                    $temp[] = $v->restore();
                    $temp['column_id'] = $v['column_id'];
                }

//                halt($temp);
                $columnObj = (new Column())::onlyTrashed()->find($temp['column_id']);
                if ($columnObj) {
                    (new Column())->restore(['id' => $columnObj['id']]);
                }
            }

            $rel = $temp;
        } else {

            $thisObj = self::onlyTrashed()->find($data[0]);
            $rel = $thisObj->restore();

            $columnObj = (new Column())::onlyTrashed()->find($thisObj['column_id']);
            if ($columnObj) {
                (new Column())->restore(['id' => $columnObj['id']]);
            }
        }
//        halt($rel);
        if (FALSE != $rel) {
            return return_json(0, '恢复成功！', 0);
        } else {
            return return_json(1, '恢复失败！');
        }
    }

    /*
     * 状态修改
     * */
    public static function mStatus($data = [])
    {
        $rel = self::update($data);
        if (FALSE != $rel) {
            return return_json(0, '修改成功！');
        } else {
            return return_json(1, '修改失败！');
        }
    }

}